<template>
  <div class="container">
    <a-card class="general-card">
      <template #title>物流设置</template>
      <template #extra>
        <a-button type="primary" @click="openCreateModal">
          <template #icon><icon-plus /></template>
          新增物流
        </a-button>
      </template>
      
      <!-- 搜索区域 -->
      <a-form :model="searchForm" class="search-form" layout="inline">
        <a-form-item field="keyword" label="关键字">
          <a-input v-model="searchForm.keyword" placeholder="公司名称/编码" allow-clear />
        </a-form-item>
        <a-form-item field="level" label="服务等级">
          <a-select v-model="searchForm.level" placeholder="全部等级" allow-clear>
            <a-option v-for="level in serviceLevels" :key="level.value" :value="level.value">{{ level.label }}</a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="status" label="状态">
          <a-select v-model="searchForm.status" placeholder="全部状态" allow-clear>
            <a-option value="1">启用</a-option>
            <a-option value="0">禁用</a-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="search">
              <template #icon><icon-search /></template>
              搜索
            </a-button>
            <a-button @click="reset">
              <template #icon><icon-refresh /></template>
              重置
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>

      <!-- 表格区域 -->
      <a-table 
        :data="logisticsCompanies" 
        :loading="companiesLoading" 
        :pagination="pagination"
        @page-change="onPageChange"
        :bordered="false"
        stripe
      >
        <template #columns>
          <a-table-column title="编号" data-index="code" :width="120" />
          <a-table-column title="公司名称" data-index="name" :width="200" />
          <a-table-column title="联系人" data-index="contact" :width="100" />
          <a-table-column title="联系电话" data-index="phone" :width="140" />
          <a-table-column title="服务等级" :width="120">
            <template #cell="{ record }">
              <a-tag :color="getLevelColor(record.level)">{{ getLevelLabel(record.level) }}</a-tag>
            </template>
          </a-table-column>
          <a-table-column title="网站" data-index="website" :width="150">
            <template #cell="{ record }">
              <a :href="record.website" target="_blank" v-if="record.website">{{ record.website }}</a>
              <span v-else>-</span>
            </template>
          </a-table-column>
          <a-table-column title="状态" :width="100">
            <template #cell="{ record }">
              <a-tag :color="record.status === 1 ? 'green' : 'red'">
                {{ record.status === 1 ? '启用' : '禁用' }}
              </a-tag>
            </template>
          </a-table-column>
          <a-table-column title="操作" fixed="right" :width="200">
            <template #cell="{ record }">
              <a-space>
                <a-button type="text" size="small" @click="openEditModal(record)">
                  编辑
                </a-button>
                <a-divider direction="vertical" />
                <a-button 
                  type="text" 
                  size="small" 
                  @click="toggleCompanyStatus(record)"
                >
                  {{ record.status === 1 ? '禁用' : '启用' }}
                </a-button>
                <a-divider direction="vertical" />
                <a-popconfirm
                  content="确定删除此物流公司吗？"
                  @ok="handleDelete(record)"
                >
                  <a-button type="text" status="danger" size="small">
                    删除
                  </a-button>
                </a-popconfirm>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>

    <!-- 新增/编辑物流弹窗 -->
    <a-modal
      v-model:visible="modalVisible"
      :title="modalType === 'create' ? '新增物流公司' : '编辑物流公司'"
      @ok="handleSubmit"
      @cancel="handleModalCancel"
      :ok-loading="submitLoading"
    >
      <a-form
        ref="formRef"
        :model="form"
        :rules="rules"
        layout="vertical"
      >
        <a-form-item field="name" label="公司名称" required>
          <a-input v-model="form.name" placeholder="请输入公司名称" allow-clear />
        </a-form-item>
        <a-form-item field="code" label="公司编号" required>
          <a-input v-model="form.code" placeholder="请输入公司编号" allow-clear />
        </a-form-item>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item field="level" label="服务等级" required>
              <a-select v-model="form.level" placeholder="请选择服务等级">
                <a-option v-for="level in serviceLevels" :key="level.value" :value="level.value">{{ level.label }}</a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="website" label="公司网站">
              <a-input v-model="form.website" placeholder="请输入公司网站" allow-clear />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item field="contact" label="联系人" required>
              <a-input v-model="form.contact" placeholder="请输入联系人姓名" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="phone" label="联系电话" required>
              <a-input v-model="form.phone" placeholder="请输入联系电话" allow-clear />
            </a-form-item>
          </a-col>
        </a-row>
        <a-form-item field="email" label="电子邮箱">
          <a-input v-model="form.email" placeholder="请输入电子邮箱" allow-clear />
        </a-form-item>
        <a-form-item field="trackingUrl" label="物流查询链接">
          <a-input v-model="form.trackingUrl" placeholder="请输入物流查询链接，使用{code}作为运单号占位符" allow-clear />
          <template #extra>例如：https://www.example.com/track?number={code}</template>
        </a-form-item>
        <a-form-item field="address" label="公司地址">
          <a-textarea v-model="form.address" placeholder="请输入公司地址" allow-clear />
        </a-form-item>
        <a-form-item field="coverage" label="服务覆盖区域">
          <a-input v-model="form.coverage" placeholder="请输入服务覆盖区域，例如：全国/华东/华南" allow-clear />
        </a-form-item>
        <a-form-item field="remark" label="备注信息">
          <a-textarea v-model="form.remark" placeholder="请输入备注信息" allow-clear />
        </a-form-item>
        <a-form-item field="status" label="状态" required>
          <a-radio-group v-model="form.status" type="button">
            <a-radio :value="1">启用</a-radio>
            <a-radio :value="0">禁用</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { Message, Modal } from '@arco-design/web-vue';
import { IconPlus, IconSearch, IconRefresh } from '@arco-design/web-vue/es/icon';
import { useLogisticsStore } from '@/stores/logistics';
import { storeToRefs } from 'pinia';

// 服务等级选项
const serviceLevels = [
  { value: 1, label: '普通服务', color: 'blue' },
  { value: 2, label: '优质服务', color: 'orange' },
  { value: 3, label: '特快服务', color: 'red' },
];

// 使用物流Store
const logisticsStore = useLogisticsStore();
const { companies: logisticsCompanies, loading: companiesLoading, pagination } = storeToRefs(logisticsStore);

// 表单相关的状态
const formRef = ref(null);
const form = reactive({
  id: undefined,
  name: '',
  code: '',
  level: 1,
  contact: '',
  phone: '',
  email: '',
  website: '',
  trackingUrl: '',
  address: '',
  coverage: '',
  remark: '',
  status: 1
});

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入公司名称' }],
  code: [
    { required: true, message: '请输入公司编号' },
    { match: /^[A-Za-z0-9-]+$/, message: '编号只能包含字母、数字和连字符' }
  ],
  level: [{ required: true, message: '请选择服务等级' }],
  contact: [{ required: true, message: '请输入联系人姓名' }],
  phone: [{ required: true, message: '请输入联系电话' }],
  status: [{ required: true, message: '请选择状态' }]
};

// 搜索表单
const searchForm = reactive({
  keyword: '',
  level: undefined,
  status: undefined
});

// 模态框状态
const modalVisible = ref(false);
const modalType = ref('create'); // 'create' 或 'edit'
const submitLoading = ref(false);

// 获取物流公司列表
const fetchLogisticsCompanies = async () => {
  const params = {
    keyword: searchForm.keyword || undefined,
    level: searchForm.level ? parseInt(searchForm.level) : undefined,
    status: searchForm.status ? parseInt(searchForm.status) : undefined,
    page: pagination.value.current,
    page_size: pagination.value.pageSize
  };
  await logisticsStore.getLogisticsCompanyList(params);
};

// 搜索操作
const search = () => {
  pagination.value.current = 1;
  fetchLogisticsCompanies();
};

// 重置搜索条件
const reset = () => {
  searchForm.keyword = '';
  searchForm.level = undefined;
  searchForm.status = undefined;
  pagination.value.current = 1;
  fetchLogisticsCompanies();
};

// 分页变化
const onPageChange = (page) => {
  logisticsStore.setCompanyPagination(page, pagination.value.pageSize);
  fetchLogisticsCompanies();
};

// 获取等级文本和颜色
const getLevelLabel = (level) => {
  const found = serviceLevels.find(item => item.value === level);
  return found ? found.label : '未知';
};

const getLevelColor = (level) => {
  const found = serviceLevels.find(item => item.value === level);
  return found ? found.color : '';
};

// 打开新增模态框
const openCreateModal = () => {
  modalType.value = 'create';
  resetForm();
  modalVisible.value = true;
};

// 打开编辑模态框
const openEditModal = (record) => {
  modalType.value = 'edit';
  Object.keys(form).forEach(key => {
    if (key in record) {
      form[key] = record[key];
    }
  });
  
  // 处理特殊字段映射
  form.trackingUrl = record.trackUrl || '';
  form.remark = record.remark || '';
  
  modalVisible.value = true;
};

// 重置表单
const resetForm = () => {
  Object.keys(form).forEach(key => {
    if (key === 'level') {
      form[key] = 1;
    } else if (key === 'status') {
      form[key] = 1;
    } else {
      form[key] = '';
    }
  });
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;
  
  try {
    // 表单验证
    await formRef.value.validate();
    submitLoading.value = true;
    
    // 准备提交的数据
    const submitData = {
      name: form.name,
      code: form.code,
      level: form.level,
      contact: form.contact,
      phone: form.phone,
      email: form.email,
      website: form.website,
      trackUrl: form.trackingUrl,
      address: form.address,
      coverage: form.coverage,
      status: form.status,
      remark: form.remark
    };
    
    let result;
    if (modalType.value === 'create') {
      result = await logisticsStore.createLogisticsCompany(submitData);
    } else {
      result = await logisticsStore.updateLogisticsCompany(form.id, submitData);
    }
    
    if (result.success) {
      Message.success(modalType.value === 'create' ? '创建物流公司成功' : '更新物流公司成功');
      modalVisible.value = false;
      fetchLogisticsCompanies(); // 刷新列表
    }
  } catch (error) {
    console.error('表单提交出错:', error);
    Message.error('提交失败，请检查表单填写是否正确');
  } finally {
    submitLoading.value = false;
  }
};

// 取消模态框
const handleModalCancel = () => {
  modalVisible.value = false;
  resetForm();
};

// 删除物流公司
const handleDelete = async (record) => {
  const result = await logisticsStore.deleteLogisticsCompany(record.id);
  if (result.success) {
    Message.success('删除成功');
    // 如果当前页只有一条数据，且不是第一页，则返回上一页
    if (logisticsCompanies.value.length === 1 && pagination.value.current > 1) {
      pagination.value.current -= 1;
    }
    fetchLogisticsCompanies(); // 刷新列表
  }
};

// 切换状态
const toggleCompanyStatus = async (record) => {
  const newStatus = record.status === 1 ? 0 : 1;
  const actionText = newStatus === 1 ? '启用' : '禁用';
  Modal.confirm({
    title: `确认${actionText}`,
    content: `确定要${actionText}物流公司 "${record.name}" 吗？`,
    okText: '确定',
    cancelText: '取消',
    onOk: async () => {
      const dataToSend = { ...record, status: newStatus };
      const result = await logisticsStore.updateLogisticsCompany(record.id, dataToSend);
      if (result.success) {
        Message.success(`${actionText}成功`);
        fetchLogisticsCompanies(); // 刷新列表
      }
    },
  });
};

// 页面加载时获取物流公司列表
onMounted(() => {
  fetchLogisticsCompanies();
});
</script>

<style lang="less" scoped>
@import '@/styles/variables.less';

.container {
  padding: 0 20px 20px 20px;
}

.general-card {
  margin-top: 16px;
  margin-bottom: 20px;
  
  :deep(.arco-card-header) {
    height: 52px;
    padding: 16px 20px;
    border-bottom: 1px solid var(--color-border);
  }
}

.search-form {
  margin-bottom: 8px;
}

:deep(.arco-modal-footer .arco-btn),
:deep(.modal-footer .arco-btn) {
  display: inline-flex;
  align-items: center;
  justify-content: center;
}
</style> 